package com.moxiao.yfjh.module.blind.utils.aliyun;


import com.alibaba.cloudapi.sdk.constant.SdkConstant;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * 阿里云学历认证服务
 */
@Slf4j
public class EducationApi {

    /**
     * 学历服务精选版  http(s)://edu.market.alicloudapi.com/education/checkplus
     * 学历服务标准版  check
     */
    public static final String PATH_URL = "https://edu.market.alicloudapi.com";
    public static final String PATH_API = "/education/checkplus";
    public static final String APPCODE = "83359fd73fe94948385f570e3c139105";
    /**
     * 头像：人脸识别 api
     */
    public static final String VERIFY_SELFIE_HOST = "https://selfiev2.market.alicloudapi.com";
    public static final String VERIFY_SELFIE_PATH = "/face/verify_selfie_idnumber";
    public static final String VERIFY_SELFIE_APPCODE = "c368c9a65dc2405e9f91fc3facd3f41a";

    // 请求方式
    public static final String POST = "POST";

    /**
     * 重要提示如下:
     * HttpUtils请从
     * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
     * 相应的依赖请参照
     * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
     */
    public static JSONObject getEducationApi(String userName, String identifyNum) {
        JSONObject jsonObject = new JSONObject();
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + APPCODE);
        Map<String, String> query = new HashMap<String, String>();
        query.put("userName", userName);
        query.put("identifyNum", identifyNum);
        String bodys = "";
        try {
            HttpResponse response = HttpUtils.doPost(PATH_URL, PATH_API, POST, headers, query, bodys);
            System.out.println(response.toString());
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
            log.info("学历认证返回：-{}", response.getEntity());
            jsonObject = getJSONObject(response.getEntity().toString());
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    public static JSONObject getJSONObject(String jsonString) {
        JSONObject jsonObject = new JSONObject(jsonString);

        // Access values from JSONObject
        String code = jsonObject.getString("code");
        String message = jsonObject.getString("message");
        String requestId = jsonObject.getString("requestId");

        // Convert nested data object to Map
        JSONObject dataObject = jsonObject.getJSONObject("data");
        String bizCode = dataObject.getString("bizCode");

        // Convert educationDetailInfo object to Map
        JSONObject educationDetailInfo = dataObject.getJSONObject("educationDetailInfo");
        String schoolType = educationDetailInfo.getString("schoolType");
        String major = educationDetailInfo.getString("major");
        String educationLevel = educationDetailInfo.getString("educationLevel");
        String admissionDate = educationDetailInfo.getString("admissionDate");
        String graduationDate = educationDetailInfo.getString("graduationDate");
        String educationType = educationDetailInfo.getString("educationType");
        // Print values or store them in a Map as needed
        System.out.println("code: " + code);
        System.out.println("message: " + message);
        System.out.println("requestId: " + requestId);
        System.out.println("bizCode: " + bizCode);
        System.out.println("schoolType: " + schoolType);
        System.out.println("major: " + major);
        System.out.println("educationLevel: " + educationLevel);
        System.out.println("admissionDate: " + admissionDate);
        System.out.println("graduationDate: " + graduationDate);
        System.out.println("educationType: " + educationType);
        return educationDetailInfo;
    }


    /**
     * 头像认证。公安人脸比对
     */
    public static String selfieIdNumberAuth(String name, String icNumber, String img) throws ExecutionException, InterruptedException {
        String result = "";
        try {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "APPCODE " + VERIFY_SELFIE_APPCODE);
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("image_url", URLEncoder.encode(img, "UTF-8"));
            bodys.put("id_number", URLEncoder.encode(name, "UTF-8"));
            bodys.put("name", URLEncoder.encode(icNumber, "UTF-8"));
            bodys.put("auto_rotate", "true");
            HttpResponse response = HttpUtils.doPost(VERIFY_SELFIE_HOST, VERIFY_SELFIE_PATH, POST, headers, querys, bodys);
            //获取response的body
            result = EntityUtils.toString(response.getEntity());
            System.out.println(response.toString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
/*


    public static void main(String[] args) {
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + VERIFY_SELFIE_APPCODE);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        String imageUrl = "https://honghe.moxiao.pro/profile/dPath/2024/02/22/20240327172027.jpg";
//        String base64Image = convertImageToBase64(imageUrl);
//        bodys.put("image", base64Image);
        bodys.put("image_url", imageUrl);
        //TODO "image"是传图片的base64编码数据，"image_url"是传图片的网络地址（确保能正常下载）。二选一即可，看您方便
        //TODO 如果传图片的base64编码数据后，返回传参错误，那有可能是编码数据被截断了，可以尝试把编码数据UrlEncode后再传参
        bodys.put("id_number", "朱毕齐");
        bodys.put("name", "342601199011022118");
        bodys.put("auto_rotate", "true");
        try {
            */

    /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
     *//*

            HttpResponse response = HttpUtils.doPost(VERIFY_SELFIE_HOST, VERIFY_SELFIE_PATH, POST, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
*/
    public static void main(String[] args) {
        String imageUrl = "https://honghe.moxiao.pro/profile/dPath/2024/02/22/20240327172027.jpg";
        String id_number = "342601199011022118";
        String name = "朱毕齐";
        try {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap = AliDemo.getResult(imageUrl, id_number, name);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static String convertImageToBase64(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            InputStream is = url.openStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int n;
            while ((n = is.read(buf)) != -1) {
                baos.write(buf, 0, n);
            }
            byte[] imageBytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }


    private static String getResultString(ApiResponse response) throws IOException {
        StringBuilder result = new StringBuilder();
        result.append("Response from backend server").append(SdkConstant.CLOUDAPI_LF).append(SdkConstant.CLOUDAPI_LF);
        result.append("ResultCode:").append(SdkConstant.CLOUDAPI_LF).append(response.getCode()).append(SdkConstant.CLOUDAPI_LF).append(SdkConstant.CLOUDAPI_LF);
        if (response.getCode() != 200) {
            result.append("Error description:").append(response.getHeaders().get("X-Ca-Error-Message")).append(SdkConstant.CLOUDAPI_LF).append(SdkConstant.CLOUDAPI_LF);
        }

        result.append("ResultBody:").append(SdkConstant.CLOUDAPI_LF).append(new String(response.getBody(), SdkConstant.CLOUDAPI_ENCODING));

        return result.toString();
    }

/*    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            String result;
            try {
                result = selfieIdNumberAuth("朱毕齐", "342601199011022118", "https://honghe.moxiao.pro/profile/dPath/2024/02/22/20240327172027.jpg");
                System.out.println("结果：" + result);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return result;
        });
        // 当API接口调用完成后，执行这段代码
        future.thenAccept(response -> {
            System.out.println("API接口的响应是：" + response);
        });
        // 这段代码会立即执行，不会等待API接口的调用
        System.out.println("这段代码会立即执行");
        // 等待异步调用完成
        future.join();


    }*/

}
